<template>
  <el-container class="app">
    <!-- 主体内容 -->
    <el-container class="app__body">
      <!-- 侧边栏导航 -->
      <Aside ref="asideRef" v-model="isCollapsed" @setMenuMap="setMenuMap" @clickItem="clickItem"></Aside>
      <!-- 主内容区 -->
      <el-main class="app__main" style="overflow: hidden">
        <!-- 头部 -->
        <el-header class="app__header">
          <!-- 折叠按钮 -->
          <el-button class="collapse-btn" type="text" @click="toggleCollapse">
            <el-icon class="collapse-icon">
              <Fold v-if="isCollapsed" />
              <Expand v-else />
            </el-icon>
          </el-button>
          <el-dropdown style="padding: 5px; float: right; margin-right: 20px">
            <div style="display: flex; align-items: center; justify-content: center; outline: none; border: none">
              <el-image
                style="width: 30px; height: 30px; border-radius: 15px; cursor: pointer"
                :src="userInfo.imageSrc"
              >
                <!-- 自定义加载失败状态为空 -->
                <template #error>
                  <div></div>
                </template>
              </el-image>
              <span style="font-size: 14px; font-weight: 700; margin-left: 2px">{{ userInfo.userName }}</span>
            </div>

            <template #dropdown>
              <el-dropdown-menu>
                <!-- <el-dropdown-item @click="handleLogout">个人中心</el-dropdown-item> -->
                <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 退出登录按钮 -->
          <!-- <el-button class="logout-btn" type="text" @click="handleLogout">
            <el-icon class="logout-icon"><SwitchButton /></el-icon>
            退出登录
          </el-button> -->
          <!-- 页签导航栏 -->
          <TabNavigation ref="tabNavigationRef" @reShow="handleReShow" />
        </el-header>
        <el-scrollbar height="calc(100vh - 70px)">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <keep-alive :exclude="currentExclude">
                <component :is="Component" :key="getTabKey($route.path)" />
              </keep-alive>
            </transition>
          </router-view>
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, getCurrentInstance, watchEffect, nextTick, onMounted } from 'vue'

import Aside from '@/components/aside/index'
import TabNavigation from '@/components/tabNavigation/index' // 引入页签导航栏组件
const { proxy } = getCurrentInstance()
const tabNavigationRef = ref(null)
const menuItem = ref({})
const localUserInfo = JSON.parse(localStorage.getItem('userInfo'))
const userInfo = ref({})
const clickItem = item => {
  menuItem.value = item
}
const setMenuMap = val => {
  tabNavigationRef.value.setMenuMap(val)
}
let storageCollapsed = true
if (JSON.parse(sessionStorage.getItem('isCollapsed')) === false) {
  storageCollapsed = false
}
const isCollapsed = ref(storageCollapsed)
watchEffect(() => {
  sessionStorage.setItem('isCollapsed', isCollapsed.value)
})
// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}
// 执行退出登录操作
const handleLogout = () => {
  // 清除本地存储中的 Token 和其他用户数据
  localStorage.removeItem('authData')

  // 跳转到登录页面
  proxy.$ToPath('/login')
}
// 维护每个路由路径对应的 key
const tabKeys = ref({})

// 获取当前路由的 key
const getTabKey = fullPath => {
  if (!tabKeys.value[fullPath]) {
    tabKeys.value[fullPath] = Date.now() // 初始化 key
  }
  return tabKeys.value[fullPath]
}

const currentExclude = ref([])

// 处理刷新事件
const handleReShow = async tab => {
  // 步骤1：临时移除缓存，触发组件卸载（onUnmounted）
  currentExclude.value.push(tab.name)
  tabKeys.value[tab.fullPath] = Date.now()
  // 步骤2：等待DOM更新，确保卸载完成
  await nextTick()

  // 步骤3：更新key并恢复缓存，触发重新挂载（onMounted）

  currentExclude.value = []
}
const getUserInfo = async userId => {
  const res = await proxy.$axios.get('/pinghai/userInfo/getAuthInfoByUserId', { userId })
  userInfo.value = {
    imageSrc: res.data.avatarUrl,
    userName: res.data.realName
  }
}
onMounted(() => {
  getUserInfo(localUserInfo?.userId)
})
</script>

<style  scoped>
/* 定义CSS变量 */
.collapse-btn {
  height: 40px;
  width: 40px;
}
.collapse-btn:hover {
  background-color: #f9f9f9;
}
.collapse-icon {
  height: 36px;
  width: 36px;
  font-size: 20px;
  color: #000;
}
.logout-btn {
  position: absolute;
  right: 0;
  margin-left: auto; /* 将退出按钮推到右侧 */
  color: #f56c6c; /* 设置退出按钮文字颜色 */
}

.logout-btn:hover {
  color: #ff0000; /* 鼠标悬停时改变颜色 */
}

.logout-icon {
  margin-right: 5px; /* 图标与文字的间距 */
}
.app {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.app__header {
  height: 70px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
  position: relative;
  z-index: 100;
}

.app__header__title {
  font-size: 1.25rem;
  font-weight: 500;
  color: #000;
  margin: 0;
}

.app__body {
  flex: 1;
  overflow: hidden;
}

.app__main {
  background: #f0f2f5;
  padding: 0px;
  overflow-y: auto;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease, transform 0.5s ease;
}

.fade-enter-from {
  opacity: 0;
  transform: translateX(-50px); /* 初始位置向上偏移 20px */
}
.fade-leave-to {
  opacity: 0;
  transform: translateX(50px); /* 初始位置向上偏移 20px */
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
  transform: translateX(0); /* 最终位置回到原点 */
}

/* 响应式设计 */
@media (max-width: 1000px) {
  .app__main {
    margin-left: 0;
    padding: 0px;
  }
}
</style>
